package miscs

import (
	"log"
	"os"
	"os/signal"
	"runtime/debug"
	"syscall"
)

// CatchRecover 捕获异常处理
func CatchRecover(fs ...func(interface{})) {
	if err := recover(); err != nil {
		log.Printf("recover err: %s\n", err)
		log.Printf("recover Stack: %s\n", debug.Stack())
		for _, f := range fs {
			f(err)
		}
	}
}

func ErrPanic(err error) {
	if err != nil {
		panic(err)
	}
}

// DefSysSigs 默认监听的系统信号
var DefSysSigs = []os.Signal{
	syscall.SIGINT,
	syscall.SIGTERM,
	syscall.SIGQUIT,
	syscall.SIGHUP,
	syscall.SIGABRT,
}

// CatchSysSig 捕获系统信号
// 捕获后处理
func CatchSysSig(f func(os.Signal), signs ...os.Signal) {
	signCh := make(chan os.Signal, 0)
	signal.Notify(signCh, signs...)
	for {
		select {
		case sig := <-signCh:
			if f != nil {
				f(sig)
			}
		}
	}
}

func CatchSysSigExit(f func(os.Signal), signs ...os.Signal) {
	signCh := make(chan os.Signal, 0)
	signal.Notify(signCh, signs...)
	for {
		select {
		case sig := <-signCh:
			if f != nil {
				f(sig)
			}
			return
		}
	}
}
